package cn.buk.qms.service;

import cn.buk.api.wechat.work.dto.AppChatCreateRequest;
import cn.buk.api.wechat.work.message.AppChatTextMessage;
import cn.buk.api.wechat.work.service.WorkWeixinService;
import cn.buk.tms.entity.base.BaseOrderInfo;
import cn.buk.tms.entity.misc.EntDepartment;
import cn.buk.tms.entity.misc.TmsWwAppChat;
import cn.buk.tms.entity.misc.User;
import cn.buk.common.util.VerifyCodeUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yfdai
 */
public abstract class BaseOrderService extends BaseAbstractService {

    /**
     * TMS的微信服务号网址
     */
    @Value("${url_tms_weixin_service}")
    protected String tmsWxsUrl;

    @Autowired
    protected WorkWeixinService wwService;

    /**
     * 判断是否超过可用信用额度
     * @param ownerId 授权者企业id
     * @param customerEnterpriseId 被授权者企业id
     * @param orderAmount 订单金额
     * @return true - 超过了可用信用额度,
     *          false - 未超过
     */
    protected boolean isOverCreditLimit(final int ownerId, final int customerEnterpriseId, final double orderAmount) {
        final double totalCreditAmount = doGetCustomerCreditAmount(ownerId, customerEnterpriseId);
        return orderAmount > totalCreditAmount;
    }

    /**
     * 发送ETERM中的Q信息到企业微信群聊会话
     */
    protected void sendEtermQueueToWwAppChat(final int enterpriseId, final String qtype, final String content) {
        doSendTextToWwAppChat(enterpriseId, EntDepartment.DEPT_CUSTOMER_SERVICE, qtype + "信息通知", qtype, content);
    }

    /**
     * 发送机票订单相关提醒
     */
    protected void sendFlightOrderAlertToWwAppChat(final int enterpriseId, final String content) {
        doSendTextToWwAppChat(enterpriseId, EntDepartment.DEPT_CUSTOMER_SERVICE, "机票订单提醒", "FLT_ORDER", content);
    }

    /**
     * 发送有新的改签单提醒
     */
    protected void sendChangeOrderAlertToWwAppChat(final int enterpriseId, final String content) {
        doSendTextToWwAppChat(enterpriseId, EntDepartment.DEPT_TICKETING,  "改签单提醒", "FLT_CHANGE", content);
    }

    /**
     * 发送有新的退票单提醒
     */
    protected void sendRefundOrderAlertToWwAppChat(final int enterpriseId, final String content) {
        doSendTextToWwAppChat(enterpriseId, EntDepartment.DEPT_TICKETING,  "退票单提醒", "FLT_REFUND", content);
    }

    /**
     * 发送CZ NDC出票相关提醒信息
     */
    protected void sendCzNdcAlertToWwAppChat(final int enterpriseId, final String content) {
        doSendTextToWwAppChat(enterpriseId, EntDepartment.DEPT_ADMINISTRATOR,  "CZ_NDC出票提醒", "CZ_NDC", content);
    }



    private void doSendTextToWwAppChat(final int enterpriseId, final int deptId, final String chatName, final String chatType, final String content) {
        var appChat = enterpriseService.searchWwAppChatByType(enterpriseId, chatType);
        if (appChat == null) {
            //创建新的群聊会话
            List<User> users = userDao.searchUsersByDepartment(enterpriseId, deptId);
            List<String> wwUsers = new ArrayList<>();
            for(User user: users) {
                if (StringUtils.isNotBlank(user.getWwUserId())) {
                    wwUsers.add(user.getWwUserId());
                }
            }
            if (wwUsers.isEmpty()) {
                return;
            }

            AppChatCreateRequest rq = new AppChatCreateRequest();
            rq.setName(chatName);
            rq.setUserList(wwUsers);

            var rs = wwService.createAppChat(enterpriseId, rq);
            if (rs.getErrcode() == 0) {
                //create success
                appChat = new TmsWwAppChat();
                appChat.setName(chatName);
                appChat.setChatId(rs.getChatId());
                appChat.setChatType(chatType);
                enterpriseService.createWwAppChat(enterpriseId, appChat);
            } else {
                //40031 不合法的UserID列表
                return;
            }
        } else {
            //TODO 使用已用的会话，需要校验是否有人应该加入群聊，有人应该退出该群聊？
        }

        AppChatTextMessage rq = new AppChatTextMessage();
        rq.setChatId(appChat.getChatId());
        rq.getText().setContent(content);

        wwService.sendAppChat(enterpriseId, rq);
    }

    /**
     * 生产模板短信用到的url和auth_code
     */
    protected String generateTmsWxsTplUrl(int enterpriseId, String openid, int orderId, String orderType) {
        final String authCode = VerifyCodeUtil.MD5(openid + "_" + enterpriseId + "_" + orderId);
        int retCode = enterpriseDao.createAuthCodeInfo(authCode, null, enterpriseId, orderType, orderId, null);
        if (retCode == 0) {
            return null;
        }

        return tmsWxsUrl + "/h5/flt/order/" + orderId + "?auth_code=" + authCode;
    }

    protected void copyFromBaseOrderInfo(BaseOrderInfo t1, BaseOrderInfo t0) {
        t1.setCustomerType(t0.getCustomerType());
        t1.setCustomer(t0.getCustomer());

        t1.setCostCenter(t0.getCostCenter());
        t1.setProjectName(t0.getProjectName());

        t1.setSupplier(t0.getSupplier());
        t1.setPaymentMethod(t0.getPaymentMethod());

        t1.setPayType(t0.getPayType());
        t1.setPayRemark(t0.getPayRemark());
    }
}
